<template>
  <div class="page-modal">
    <!-- <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="30%"
      center
      destroy-on-close
    >
      <HyForm v-bind="props.pageModalConfig" v-model="formData"></HyForm>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmClick">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog> -->
    <HyDialog
      :title="title"
      ref="hyDialogRef"
      @handleConfirmClick="handleConfirmClick"
    >
      <template #content>
        <HyForm v-bind="props.pageModalConfig" v-model="formData"></HyForm>
        <slot></slot>
      </template>
    </HyDialog>
  </div>
</template>

<script setup lang="ts">
import HyDialog from '@/base-ui/HyDialog/hy-dialog.vue';
import HyForm from '@/base-ui/HyForm/hy-form.vue';
import { ref, watch } from 'vue';
import { useStore } from 'vuex';
const store = useStore();
const props = defineProps({
  pageModalConfig: {
    type: Object,
    required: true
  },
  defaultFormData: {
    type: Object,
    required: true
  },
  pageName: {
    type: String,
    required: true
  },
  otherInfo: {
    type: Object,
    default: () => ({})
  }
});
const hyDialogRef = ref<InstanceType<typeof HyDialog>>();
const formItems = props.pageModalConfig.formItems ?? [];
const title = ref('');
const formData = ref<any>({});
watch(
  () => props.defaultFormData,
  (newVal) => {
    console.log(newVal);
    for (const item of formItems) {
      formData.value[`${item.field}`] = newVal[`${item.field}`];
    }
  }
);

const handleConfirmClick = () => {
  if (Object.keys(props.defaultFormData).length) {
    // 编辑
    store.dispatch('system/editData', {
      pageName: props.pageName,
      data: { ...formData.value, ...props.otherInfo },
      id: props.defaultFormData.id
    });
  } else {
    // 新建
    store.dispatch('system/createData', {
      pageName: props.pageName,
      data: { ...formData.value, ...props.otherInfo }
    });
  }
  dialogVisible.value = false;
};
const dialogVisible = ref(false);
defineExpose({
  dialogVisible,
  hyDialogRef,
  title
});
</script>

<style scoped></style>
